﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IFRS.Web;
using System.Web.Security;
using System.DirectoryServices;
using System.Configuration;
using IFRS.DataAccess.DAL;
using System.Data;
public partial class Login : System.Web.UI.Page
{

    #region "---------- Property -----------"

    private ADUSER _ADUSER = null;
    private ADUSER ADUSER
    {
        get
        {
            if (_ADUSER == null)
            {
                _ADUSER = new ADUSER();
            }

            return _ADUSER;
        }
    }

    #endregion

    #region "---------- Events -------------"

    protected override void OnError(EventArgs e)
    {
        Exception ex = HttpContext.Current.Server.GetLastError();

        HttpContext ctx = HttpContext.Current;

        Exception exception = ctx.Server.GetLastError();

        string errorInfo =
        "-----------------------------Error url-------------------------------------" + Environment.NewLine + ctx.Request.Url.ToString() + Environment.NewLine +
        "---------------------------------------------------------------------------" + Environment.NewLine +
        "" + Environment.NewLine +
        "---------------------------Error message---------------------------------" + Environment.NewLine + exception.Message + Environment.NewLine +
        "---------------------------------------------------------------------------" + Environment.NewLine +
        "" + Environment.NewLine +
        "-----------------------------Error line-------------------------------------" + Environment.NewLine + exception.StackTrace + Environment.NewLine +
        "--------------------------------------------------------------------------";

        Log.logger.Error(ctx.Request.Url.ToString(), ex);
        base.OnError(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnLogIn_Click(object sender, EventArgs e)
    {
        //TestLogin();
        FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), false);
        Response.Redirect("~/Index/Index.aspx");
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }

    #endregion

    #region "---------- Methods ------------"

    private string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    private void TestLogin()
    {
        string[] arrBRANCH = null;
        string sBRANCH = "CN=Npa001,OU=Executive,OU=Branches,DC=gsbnetdev,DC=be2456dev,DC=ramjittidev";
        arrBRANCH = Array.ConvertAll(sBRANCH.Split(','), p => p.Trim());

        SessionManager.IFRS_EMPLOYEE_ID = "5600001";
        SessionManager.IFRS_EMPLOYEE_NAME = "สุกชัย แสนจน";
        SessionManager.IFRS_EMPLOYEE_DES = "หน่วยงานทวงเงิน";
        SessionManager.IFRS_COST_CENTER = "999";
        SessionManager.IFRS_BRANCH = arrBRANCH[2];

        SessionManager.IFRS_ROLE_ID = ADUSER.SEARCH_BYID_ROLEGROUPUSER(SessionManager.IFRS_EMPLOYEE_ID, SessionManager.IFRS_BRANCH);

        if (SessionManager.IFRS_ROLE_ID > 0)
        {
            FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), false);
            Response.Redirect("~/Index/Index.aspx");
        }
        else
        {
            Utility.AlertMessage(Page, Resources.ifrsResource.MessageFailLogin);
        }
    }

    private string LoginAD()
    {
        string sError = "";
        string DomainAndUsername = "";
        string strCommu;
        strCommu = ("LDAP://"
                    + (IFRS_Global.AD.LDAPServer + ("/" + IFRS_Global.AD.LDAPPath)));
        DomainAndUsername = (IFRS_Global.AD.DomainName + ("\\" + txtUserName.Text));
        DirectoryEntry entry = new DirectoryEntry(strCommu, DomainAndUsername, txtPassword.Text);
        object obj;

        try
        {
            obj = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);
            SearchResult result;
            search.Filter = ("(SAMAccountName="
                        + (txtUserName.Text + ")"));
            search.PropertiesToLoad.Add("cn");
            result = search.FindOne();

            if ((result != null))
            {
                SessionManager.IFRS_EMPLOYEE_ID =  GetProperty(result, "employeeID");
                SessionManager.IFRS_EMPLOYEE_NAME = GetProperty(result, "name");
                SessionManager.IFRS_EMPLOYEE_DES = GetProperty(result, "description");
                SessionManager.IFRS_BRANCH = GetProperty(result, "distinguishedName");
                SessionManager.IFRS_COST_CENTER = GetProperty(result, "postalCode");
            }
            else
            {
                Response.Write("Can't People in Domain");
            }
        }
        catch(Exception ex)
        {
            throw (ex);
        }

        return sError;
    }

    private void CheckLoginAD()
    {
        string DomainAndUsername = "";
        string strCommu;
        strCommu = ("LDAP://"
                 + (IFRS_Global.AD.LDAPServer + ("/" + IFRS_Global.AD.LDAPPath)));
        DomainAndUsername = (IFRS_Global.AD.DomainName + ("\\" + txtUserName.Text));
        try
        {
            DirectoryEntry entry = new DirectoryEntry(strCommu, DomainAndUsername, txtPassword.Text);

            DirectorySearcher dSearch = new DirectorySearcher(entry);
            //dSearch.Filter = "(&(objectClass=user))";
            dSearch.Filter = string.Format("(&(objectCategory=user)(|(CN={0})(sAMAccountName={0})))", txtUserName.Text);
            // get all entries from the active directory.
            // Last Name, name, initial, homepostaladdress, title, company etc..
            string sOuTemp1 = "";
            string sOuTemp2 = "";
            string sOu = "";
            foreach (SearchResult sResultSet in dSearch.FindAll())
            {
                // distinguishedName
                Response.Write("<b>DistinguishedName :</b>" + GetProperty(sResultSet, "distinguishedName"));
                Response.Write("<br/>");

                sOuTemp1 = GetProperty(sResultSet, "distinguishedName");


                int i = sOuTemp1.Trim().IndexOf("OU=");

                if (i != -1)
                {
                    sOuTemp2 = sOuTemp1.Substring(i + 3, sOuTemp1.Length - i - 3);

                    i = sOuTemp2.Trim().IndexOf(",OU=");

                    if (i != -1)
                        sOu = sOuTemp2.Substring(0, i);
                    else
                        sOu = sOuTemp2;
                }
                else
                    sOu = "";

                Response.Write("<b>OU :</b>" + sOu);
                Response.Write("<br/>");

                // Login Name
                Response.Write("<b>Login Name :</b>" + GetProperty(sResultSet, "cn"));
                Response.Write("<br/>");
                // sAMAccountName
                Response.Write("<b>sAMAccountName :</b>" + GetProperty(sResultSet, "sAMAccountName"));
                Response.Write("<br/>");
                // First Name
                Response.Write("<b>First Name :</b>" + GetProperty(sResultSet, "givenName"));
                Response.Write("<br/>");
                // Middle Initials
                Response.Write("<b>Middle Initials :</b>" + GetProperty(sResultSet, "initials"));
                Response.Write("<br/>");
                // Last Name
                Response.Write("<b>Last Name :</b>" + GetProperty(sResultSet, "sn"));
                Response.Write("<br/>");
                // Address
                string tempAddress = GetProperty(sResultSet, "homePostalAddress");

                if (tempAddress != string.Empty)
                {
                    string[] addressArray = tempAddress.Split(';');
                    string taddr1, taddr2;
                    taddr1 = addressArray[0];
                    Response.Write("<b>Address 1 :</b>" + taddr1);
                    Response.Write("<br/>");
                    taddr2 = addressArray[1];
                    Response.Write("<b>Address 2 :</b>" + taddr2);
                    Response.Write("<br/>");
                }
                // title
                Response.Write("<b>Title :</b>" + GetProperty(sResultSet, "title"));
                Response.Write("<br/>");
                // company
                Response.Write("<b>Company :</b>" + GetProperty(sResultSet, "company"));
                Response.Write("<br/>");
                //state
                Response.Write("<b>State :</b>" + GetProperty(sResultSet, "st"));
                Response.Write("<br/>");
                //city
                Response.Write("<b>City :</b>" + GetProperty(sResultSet, "l"));
                Response.Write("<br/>");
                //country
                Response.Write("<b>Country :</b>" + GetProperty(sResultSet, "co"));
                Response.Write("<br/>");
                //postal code
                Response.Write("<b>Postal code :</b>" + GetProperty(sResultSet, "postalCode"));
                Response.Write("<br/>");
                // telephonenumber
                Response.Write("<b>Telephonenumber :</b>" + GetProperty(sResultSet, "telephoneNumber"));
                Response.Write("<br/>");
                //extention
                Response.Write("<b>Extention :</b>" + GetProperty(sResultSet, "otherTelephone"));
                Response.Write("<br/>");
                //fax
                Response.Write("<b>Fax :</b>" + GetProperty(sResultSet, "facsimileTelephoneNumber"));
                Response.Write("<br/>");
                // Email address
                Response.Write("<b>Email address :</b>" + GetProperty(sResultSet, "mail"));
                Response.Write("<br/>");
                // Challenge Question
                Response.Write("<b>Challenge Question :</b>" + GetProperty(sResultSet, "extensionAttribute1"));
                Response.Write("<br/>");
                // Challenge Response
                Response.Write("<b>Challenge Response :</b>" + GetProperty(sResultSet, "extensionAttribute2"));
                Response.Write("<br/>");
                //Member Company
                Response.Write("<b>Member Company :</b>" + GetProperty(sResultSet, "extensionAttribute3"));
                Response.Write("<br/>");
                // Company Relation ship Exits
                Response.Write("<b>Company Relation ship Exits :</b>" + GetProperty(sResultSet, "extensionAttribute4"));
                Response.Write("<br/>");
                //status
                Response.Write("<b>status :</b>" + GetProperty(sResultSet, "extensionAttribute5"));
                Response.Write("<br/>");
                // Assigned Sales Person
                Response.Write("<b>Assigned Sales Person :</b>" + GetProperty(sResultSet, "extensionAttribute6"));
                Response.Write("<br/>");
                // Accept T and C
                Response.Write("<b>Accept T and C :</b>" + GetProperty(sResultSet, "extensionAttribute7"));
                Response.Write("<br/>");
                // jobs
                Response.Write("<b>jobs :</b>" + GetProperty(sResultSet, "extensionAttribute8"));
                Response.Write("<br/>");
                String tEamil = GetProperty(sResultSet, "extensionAttribute9");

                // email over night
                if (tEamil != string.Empty)
                {
                    string em1, em2, em3;
                    string[] emailArray = tEamil.Split(';');
                    em1 = emailArray[0];
                    em2 = emailArray[1];
                    em3 = emailArray[2];
                    Response.Write("<b>email over night :" + em1 + em2 + em3);
                    Response.Write("<br/>");
                }
                // email daily emerging market
                Response.Write("<b>email daily emerging market :</b>" + GetProperty(sResultSet, "extensionAttribute10"));
                Response.Write("<br/>");
                // email daily corporate market
                Response.Write("<b>email daily corporate market :</b>" + GetProperty(sResultSet, "extensionAttribute11"));
                Response.Write("<br/>");
                // AssetMgt Range
                Response.Write("<b>AssetMgt Rangee :</b>" + GetProperty(sResultSet, "extensionAttribute12"));
                Response.Write("<br/>");
                // date of account created
                Response.Write("<b>date of account created :</b>" + GetProperty(sResultSet, "whenCreated"));
                Response.Write("<br/>");
                // date of account changed
                Response.Write("<b>date of account changed :</b>" + GetProperty(sResultSet, "whenChanged"));
                Response.Write("<br/>");
            }

        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    #endregion


}